package widget_data

import "encoding/xml"

type Root struct {
	XMLName xml.Name `xml:"root"`
	//SkinTempName   string       `xml:"SkinTempName,attr"`
	ChildrenWidget []*WidgetData `xml:",any"`
	//ChildrenWidget []WidgetData `xml:"LoadSkin|Widget"`
	Properties []*Property `xml:"Property"`
	LoadSkin   LoadSkin    `xml:"LoadSkin"`
	//Properties     []Property   `xml:"Property"`
}

type WidgetData struct {
	XMLName        xml.Name
	Name           string        `xml:"Name,attr"`
	ChildrenWidget []*WidgetData `xml:"Widget"`
	SkinTempName   string        `xml:"SkinTempName,attr"`
	Properties     []*Property   `xml:"Property"`
}

type Property struct {
	Key   string `xml:"Key,attr"`
	Value string `xml:"Value,attr"`
}
type LoadSkin struct {
	Skin string `xml:"Skin,attr"`
}
type IParser interface {
	UpdateProperties(prop []*Property)
	UpdateLoadSkin(skinInfo *LoadSkin)
	StartElement(ctx interface{}, name string, atts interface{})
	EndElement(ctx interface{}, name string, atts interface{})
}

type IWidgetLoader interface {
	Load(data []byte)
}

type SkinRoot struct {
	XMLName        xml.Name   `xml:"root"`
	ChildrenWidget []SkinData `xml:",any"`
}

type SkinData struct {
	TemplateName string            //模板名字
	SkinName     string            `xml:"Name,attr"`
	AttributeMap map[string]string `xml:",any"`
	Properties   []*Property       `xml:"Property"`
	//ChildrenWidget []SkinData        `xml:",any"`
}

func (p *Property) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
	for _, attr := range start.Attr {
		if attr.Name.Local == "Key" {
			p.Key = attr.Value
		} else if attr.Name.Local == "Value" {
			p.Value = attr.Value
		}
	}

	if err := d.Skip(); err != nil {
		return err
	}
	return nil
}
func (s *SkinData) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
	s.AttributeMap = make(map[string]string)
	s.Properties = make([]*Property, 0)
	aux := struct {
		XMLName xml.Name
		//SkinName       string      `xml:"Name,attr"`
		Properties []*Property `xml:"Property"`
	}{
		XMLName: start.Name,
	}

	for _, attr := range start.Attr {
		if attr.Name.Local == "Name" {
			s.SkinName = attr.Value
		} else {
			s.AttributeMap[attr.Name.Local] = attr.Value
		}
	}
	// 解析子元素
	if err := d.DecodeElement(&aux, &start); err != nil {
		return err
	}
	s.TemplateName = aux.XMLName.Local
	s.Properties = append(s.Properties, aux.Properties...)
	return nil
}

func (l *LoadSkin) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
	for _, attr := range start.Attr {
		if attr.Name.Local == "Skin" {
			l.Skin = attr.Value
		}
	}

	if err := d.Skip(); err != nil {
		return err
	}
	return nil
}
func CastPropertyToMap(prop []*Property) map[string]string {
	tmp := map[string]string{}
	for _, v := range prop {
		tmp[v.Key] = v.Value
	}
	return tmp
}
